package com.qidian.qc.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.qidian.mes.pojo.qc.QcIndex;
import com.qidian.mes.util.pojo.MESResult;
import com.qidian.qc.mapper.QcDefectMapper;
import com.qidian.qc.mapper.QcIndexMapper;
import com.qidian.qc.service.QcIndexService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Calendar;
import java.util.List;

/**
 * @Author 53邹李萍
 * @Company 起点编程
 * @Time 2023/10/30 16:21
 * @Description
 */
@Service
@Transactional
public class QcIndexServiceImpl implements QcIndexService {
    @Autowired
    QcIndexMapper qcIndexMapper;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    //分页查询
    @Override
    public MESResult list(int page, int list, QcIndex qcIndex) {
        PageHelper.startPage(page,list);
        List<QcIndex> list1=qcIndexMapper.list(qcIndex);
        PageInfo<QcIndex> pageInfo=new PageInfo<>(list1);
        return MESResult.ok(pageInfo);
    }
//增加
    @Override
    public MESResult save(QcIndex qcIndex) {
        QcIndex qcIndex2=qcIndexMapper.getAllByIndexCode(qcIndex.getIndexCode());
        if (qcIndex2!=null){
            return MESResult.duplicate("重复");
        }
        return MESResult.updateIsOk(qcIndexMapper.save(qcIndex));
    }

    //修改
    @Override
    public MESResult update(QcIndex qcIndex) {
        QcIndex qcIndex2=qcIndexMapper.getAllByIndexCode(qcIndex.getIndexCode());
        if (qcIndex2!=null){
            return MESResult.duplicate("编号重复");
        }
        return MESResult.updateIsOk(qcIndexMapper.update(qcIndex));
    }

    @Override
    public MESResult getIndexCode(String indexCode) {

        if (qcIndexMapper.getAllByIndexCode(indexCode)!=null){
            return MESResult.ok(qcIndexMapper.getAllByIndexCode(indexCode));
        }
        return MESResult.empty();
    }

    @Override
    public MESResult delete(String indexCode) {

        return MESResult.updateIsOk(qcIndexMapper.delete(indexCode));
    }

    //自生成
    @Override
    public MESResult generate() {
        String key = "indexId";
// 生产编号的业务应该写在service中，我们这里因为时间关系，就直接写这里
        StringBuilder id = new StringBuilder();
// 固定部分-可能需要从数据库查询
        id.append("l");
// 时间
        Calendar calendar = Calendar.getInstance();
        id.append(calendar.get(Calendar.YEAR) + "" + (calendar.get(Calendar.MONTH) + 1) + calendar.get(Calendar.DATE));
// 从redis获取序列
        Long idTemp = stringRedisTemplate.opsForValue().increment(key);
        String idStr = idTemp.toString();
        if(idStr.length() < 5){
// 前面加0
            for (int i = 0;i < 5 - idStr.length();i++){
                idStr = "0" + idStr;
            }
        }
        id.append(idStr);
        return MESResult.ok(id);
    }


}
